package com.paygate

import cn.hutool.core.io.IoUtil
import cn.hutool.extra.spring.SpringUtil
import freemarker.cache.StringTemplateLoader
import freemarker.template.Configuration
import freemarker.template.Template
import org.springframework.context.annotation.Bean
import org.springframework.core.io.ClassRelativeResourceLoader
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
import java.io.StringWriter
import java.math.BigDecimal
import java.math.RoundingMode
import kotlin.contracts.ExperimentalContracts
import kotlin.contracts.contract
import kotlin.text.Charsets.UTF_8

@org.springframework.context.annotation.Configuration
open class WebConfig : WebMvcConfigurer {

    override fun addViewControllers(registry: ViewControllerRegistry) {
        super.addViewControllers(registry)
    }

    /**
     * 模板配置
     */
    @Bean
    open fun freemarkerConfig(): Configuration {
        val configuration = Configuration(Configuration.VERSION_2_3_29)
        configuration.templateLoader = StringTemplateLoader()
        configuration.defaultEncoding = "utf-8"
        return configuration
    }
}

/**
 * 处理模板
 */
private fun processTemplate(tpContent: string, map: Map<string, *>): String {
    val configuration = SpringUtil.getBean(Configuration::class.java)
    val template = Template("template", tpContent, configuration)
    val sw = StringWriter()
    template.process(map, sw)
    return sw.toString()
}

fun getCheckoutPage(map: Map<string, *>) =
    ClassRelativeResourceLoader(WebConfig::class.java).run {
        val resource = getResource("classpath:/template/checkout.ftl").inputStream
        val tpContent = IoUtil.read(resource, UTF_8)
        processTemplate(tpContent, map)
    }

@ExperimentalContracts
fun Any?.isNotNull(): Boolean {
    contract {
        returns(true) implies (this@isNotNull != null)
    }
    return this != null
}

fun scale(d: double?) = BigDecimal.valueOf(d!!.toDouble()).setScale(2, RoundingMode.HALF_UP).toString()
fun scale(v:string?) = scale(v!!.toDouble())
